
package us.hornerscorners.lollipop.hapi;

/*
 * #%L
 * LollipopRouter
 * %%
 * Copyright (C) 2013 - 2014 Jim Horner
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */

import ca.uhn.hl7v2.HL7Exception;

import ca.uhn.hl7v2.model.Composite;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Primitive;
import ca.uhn.hl7v2.model.Segment;
import ca.uhn.hl7v2.model.Structure;
import ca.uhn.hl7v2.model.Type;

import com.google.common.base.Function;
import com.google.common.base.Strings;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import us.hornerscorners.lollipop.config.RoutingConfig;


/**
 * Class description
 *
 *
 * @version        v1.0, 2014-09-07
 * @author         Jim Horner
 */
public class Message2RoutingTransformer implements Function<Message, RoutingConfig> {

    /** Field description */
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Method description
     *
     *
     * @param msg
     *
     * @return
     */
    @Override
    public RoutingConfig apply(Message msg) {

        RoutingConfig result = new RoutingConfig();

        result.setVersion(msg.getVersion());

        try {

            Structure mshstruct = msg.get("MSH");

            if (mshstruct instanceof Segment) {

                Segment msh = (Segment) mshstruct;

                result.setSendingApplication(getHdValue(msh, 3));
                result.setSendingFacility(getHdValue(msh, 4));
                result.setReceivingApplication(getHdValue(msh, 5));
                result.setReceivingFacility(getHdValue(msh, 6));

                Type msgtype = msh.getField(9, 0);

                if (msgtype instanceof Composite) {

                    Composite msgcomp = (Composite) msgtype;

                    result.setMessageType(getIdValue(msgcomp, 0));
                    result.setTriggerEvent(getIdValue(msgcomp, 1));
                }
            }
        } catch (Exception e) {

            logger.warn("Unable to parse message to routing config.");
        }

        return result;
    }

    /**
     * Method description
     *
     *
     * @param seg
     * @param fieldNumber
     *
     * @return
     *
     * @throws HL7Exception
     */
    private String getHdValue(Segment seg, int fieldNumber) throws HL7Exception {

        String result = null;

        Type type = seg.getField(fieldNumber, 0);

        if (type instanceof Composite) {

            Type comtype = ((Composite) type).getComponent(0);

            if (comtype instanceof Primitive) {

                result = ((Primitive) comtype).getValue();
                
            } else {

                logger.warn("Composite 0 not a Primitive type, instead {}",
                            type.getClass());
            }

        } else {

            logger.warn("Field not a Composite type, instead {}", type.getClass());
        }

        return Strings.emptyToNull(result);
    }

    /**
     * Method description
     *
     *
     * @param comp
     * @param fieldNumber
     *
     * @return
     *
     * @throws DataTypeException
     */
    private String getIdValue(Composite comp, int fieldNumber) throws DataTypeException {

        String result = null;

        Type type = comp.getComponent(fieldNumber);

        if (type instanceof Primitive) {

            result = ((Primitive) type).getValue();
        } else {

            logger.warn("ID value not a Primitive type, instead {}", type.getClass());
        }

        return Strings.emptyToNull(result);
    }
}
